package com.example.mediaandroidjava;

import static android.os.storage.StorageManager.ACTION_MANAGE_STORAGE;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.media3.common.MediaItem;
import androidx.media3.database.StandaloneDatabaseProvider;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DefaultHttpDataSource;
import androidx.media3.datasource.cache.CacheDataSource;
import androidx.media3.datasource.cache.NoOpCacheEvictor;
import androidx.media3.datasource.cache.SimpleCache;
import androidx.media3.exoplayer.DefaultRenderersFactory;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.offline.Download;
import androidx.media3.exoplayer.offline.DownloadHelper;
import androidx.media3.exoplayer.offline.DownloadManager;
import androidx.media3.exoplayer.offline.DownloadRequest;
import androidx.media3.exoplayer.offline.DownloadService;
import androidx.media3.exoplayer.scheduler.Requirements;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.storage.StorageManager;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.Executor;

public class DownloadMediaActivity extends AppCompatActivity {
    private ExoPlayer player;
    private StandaloneDatabaseProvider databaseProvider;
    private SimpleCache downloadCache;
    private String downloadDirectory = "/";
    private DefaultHttpDataSource.Factory dataSourceFactory;
    private DownloadManager downloadManager;
    private Requirements requirements;

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_media);
        ///手动获取权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.FOREGROUND_SERVICE}, 1);
        } else {
            addDownloadTask("id001", Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"), this);
        }
    }

    ///创建下载管理器
//    private void createDownloadManager(Context context) {
//        databaseProvider = new StandaloneDatabaseProvider(context);
//        downloadCache = new SimpleCache(new File(downloadDirectory), new NoOpCacheEvictor(), databaseProvider);
//        dataSourceFactory = new DefaultHttpDataSource.Factory();
//        Executor downloadExecutor = Runnable::run;
//        downloadManager = new DownloadManager(context, databaseProvider, downloadCache, dataSourceFactory, downloadExecutor);
//        downloadManager.setRequirements(requirements);
//        downloadManager.setMaxParallelDownloads(3);
//    }

    ///添加下载任务
    private void addDownloadTask(String contentId, Uri contentUri, Context context) {
        DownloadRequest downloadRequest = new DownloadRequest.Builder(contentId, contentUri).build();
        DownloadService.sendAddDownload(context, MyDownloadService.class, downloadRequest, /* foreground= */ false);
    }

    ///删除下载
    private void deleteDownload(Context context, String contentId) {
        DownloadService.sendRemoveDownload(context, MyDownloadService.class, contentId, /* foreground= */ false);
    }

    ///停止下载
    private void stopSingleDownloadReason(Context context, String contentId, int stopReason) {
        DownloadService.sendSetStopReason(context, MyDownloadService.class, contentId, stopReason, /* foreground= */ false);
        DownloadService.sendSetStopReason(context, MyDownloadService.class, contentId, Download.STOP_REASON_NONE,
                /* foreground= */ false);
    }

    ///暂停下载
    private void pauseOrResumeDownloads(Context context) {
        DownloadService.sendPauseDownloads(context, MyDownloadService.class, /* foreground= */ false);
        DownloadService.sendResumeDownloads(context, MyDownloadService.class, /* foreground= */ false);
    }

    ///设置Requirement
    private void setDownloadRequirement(Context context) {
        DownloadService.sendSetRequirements(context, MyDownloadService.class, requirements,
                /* foreground= */ false);
    }

    ///监听
    private void addListener() {
        downloadManager.addListener(new DownloadManager.Listener() {
        });
    }

    ///播放下载缓存视频
    private void playDownloadCache(DataSource.Factory httpDataSourceFactory, Context context, String contentUri) {
        DataSource.Factory cacheDataSourceFactory = new CacheDataSource.Factory().setCache(downloadCache).setUpstreamDataSourceFactory(httpDataSourceFactory).setCacheWriteDataSinkFactory(null); // Disable writing.
        ExoPlayer player = new ExoPlayer.Builder(context).setMediaSourceFactory(new DefaultMediaSourceFactory(context).setDataSourceFactory(cacheDataSourceFactory)).build();
        ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory).createMediaSource(MediaItem.fromUri(contentUri));
        player.setMediaSource(mediaSource);
        player.prepare();
    }

    ///下载和播放自适应流
    private void downloadStream(Context context, String contentUri, DownloadHelper.Callback callback) {
        DownloadHelper downloadHelper = DownloadHelper.forMediaItem(context, MediaItem.fromUri(contentUri), new DefaultRenderersFactory(context), dataSourceFactory);
        ;
        downloadHelper.prepare(callback);
    }
}